<?php

/**
 * Created by PhpStorm.
 * User: wanglin
 * Date: 2018/11/15
 * Time: 11:09
 */

namespace App\Services;


use App\Models\PartnerTip;
use App\Services\ThirdAPI\GameApiService;
use common\enum\CommonEnum;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use common\utils\SysCode;


class PartanerTips
{
    const API = 'BG';
    const TYPE = 2;

    /**
     * 处理BG小费数据
     * @param $data
     */
    public static function handleData($data)
    {
        if (empty($data)) {
            return;
        }
        foreach ($data as $value) {
            static::saveData($value);
        }
    }

    public static function saveData($data)
    {
        $tipInfo = DB::table("partner_tips")->where(['staff_no' => $data['staffNo'], 'partner_account' => $data['loginId'], 'operator_time' => $data['createTime'], 'partner_name' => self::API])->first()->toArray();
        if (!empty($tipInfo)) {
            $model = PartnerTip::find($tipInfo['id']);
        } else {
            $model = new PartnerTip();
        }
        $userInfo = UserService::getUserAgentInfoByApiName($data['loginId']);
        $info = GameApiService::getApiPartnerInfoByName(self::API);
        if (is_object($info)) {
            $info = $info->toArray();
        }
        $model->hall_id = intval(static::getHallIDFromName($data['loginId']));
        $model->user_id = intval($userInfo['id'] ?? 0);
        $model->username = $userInfo['username'] ?? "平台用户";
        $model->partner_account = $data['loginId'];
        $model->partner_id = intval($info['id']);
        $model->partner_name = self::API;
        $model->game_code = '';
        $model->game_name = '';
        $model->type = self::TYPE;
        $model->amount = $data['amount'] * CommonEnum::MONEY_RATE;
        $model->staff_no = $data['staffNo'];
        $model->operator_time = $data['createTime'];
        if (!$model->save()) {
            $msg = self::API . "小费拉取失败需要重新拉取" . date("Y-m-d H:i:s");
            Log::error($msg, $data);
            return error_exit(SysCode::INTERNAL_SERVER_ERROR, $msg);
        }
    }

    /**
     * 根据用户名解析出厅ID
     * prod_fg_80_1234
     * prodXfgX80X1234
     *
     */
    public static function getHallIDFromName($name)
    {
        $splits = ['_', 'X'];
        foreach ($splits as $s) {
            $arr = explode($s, $name);
            if (count($arr) > 3) {
                return $arr[2];
            }
        }
        return 80;
    }


}